package com.wtwd.campus.receiver;

import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.dao.CommandRecordMapper;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.service.DeviceAppService;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.utils.ReceiverUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author mjy
 * @date 2022/12/15
 * @description
 */
@Service
@MsgType(value = Constants.APP_DISABLE)
public class SetAppDisableReceiverHandler implements IReceiverHandler {


    @Resource
    private DeviceInfoService deviceInfoService;

    @Resource
    private DeviceAppService deviceAppService;

    @Resource
    private CommandRecordMapper commandRecordMapper;

    @Resource
    private ReceiverUtils receiverUtils;

    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqAppDisable mqAppDisable = (MqAppDisable) mqMessage.getObject();
        String imei = mqAppDisable.getImei();
        String commandNumber = mqAppDisable.getCommandNumber();
        String cmd=Constants.APP_DISABLE.concat("-").concat(mqAppDisable.getPackageName());
        DeviceInfo deviceInfo = deviceInfoService.getDeviceByImei(imei);
        String date = mqAppDisable.getDeviceDate();
        String time = mqAppDisable.getDeviceTime();
        Long time1 = getTime(date, time);
        if (deviceInfo != null) {
            //根据流水号，imei号，和指令类型找到唯一的一条指令记录
            CommandRecord commandRecord = commandRecordMapper.getCommandRecordByCondition2(imei, commandNumber, cmd);
            if (commandRecord != null) {//处理业务
                List<MqAppDisableTime> mqAppDisableTime = mqAppDisable.getMqAppDisableTime();
                int flag = mqAppDisable.getFlag();
                String packageName = mqAppDisable.getPackageName();
                deviceAppService.dealAppDisable(deviceInfo.getDeviceId(), packageName, flag,mqAppDisableTime);
                //修改设备信息
                deviceInfo.setLastUpTime(System.currentTimeMillis());
                deviceInfoService.modifyDeviceInfo(deviceInfo);
                //删除缓存中的指令
                String delKey = cmd.concat("-").concat(commandNumber);
                receiverUtils.deleteCommandInRedis(imei, delKey);
                //完善指令下发记录
                receiverUtils.completeCommandRecord(cmd, imei, commandNumber, null, Constants.COMMAND_COMPLETE, time1);
            }
        }
        return;
    }
}
